﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Engine
{
    /// <summary>
    /// XML Serialization for default XML files
    /// </summary>
    public static class XMLHandler
    {
        public static void Serialize<T>(string filename, T data)
        {
            XmlSerializer x = new XmlSerializer(data.GetType());

            try
            {
                if (File.Exists(filename))
                    File.Delete(filename);
                Stream file = File.OpenWrite(filename);
                x.Serialize(file, data);
                file.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Couldn't Serialize to file: " + filename + ". \n Error: " + e.Message);   
            }            
        }

        public static T Deserialize<T>(string filename)
        {
            Stream file = null;
            try
            {
                file = File.Open(filename, FileMode.Open);
                XmlSerializer x = new XmlSerializer(typeof(T));
                T data = (T)x.Deserialize(file);
                file.Close();
                return data;
            }
            catch (Exception e)
            {
                if(file != null)
                    file.Close();
                Console.WriteLine("Couldn't Deserialize from file: " + filename + ". \n Error: " + e.Message);
                return default(T);
            }       
        }
    }
}